package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.holder.UserHolder;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @program: sky-take-out
 * @description:
 * @author: 酷炫焦少
 * @create: 2024-11-18 19:10
 **/
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private AddressBookMapper addressBookMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private ShoppingCartMapper shoppingCartMapper;

    @Resource
    private OrderDetailMapper orderDetailMapper;

    @Resource
    private WebSocketServer webSocketServer;

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;

    @Override
    @Transactional
    public Result<OrderSubmitVO> submit(OrdersSubmitDTO submitDTO) {
        if (Objects.isNull(submitDTO)) {
            return Result.error("下单失败");
        }
        // 获得用户id
        Long userId = UserHolder.get();
        // 获得收货人地址
        Long addressBookId = submitDTO.getAddressBookId();
        if (Objects.isNull(addressBookId)) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        AddressBook addressBook = AddressBook.builder().id(addressBookId).build();
        AddressBook addressByUserId = addressBookMapper.getOne(addressBook);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(userId);
        if (CollectionUtil.isEmpty(shoppingCartList)) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        // 检查用户的收货地址是否超出配送范围
        checkOutOfRange(addressByUserId.getProvinceName() + addressByUserId.getCityName()
                + addressByUserId.getDistrictName() + addressByUserId.getDetail());
        // 生成一个订单号
        long number = System.currentTimeMillis();
        String address = addressByUserId.getProvinceName() + addressByUserId.getCityName()
                + addressByUserId.getDistrictName() + addressByUserId.getDetail();
        // 获得下单用户信息
        User user = userMapper.getOne(User.builder().id(userId).build());
        Orders orders = BeanUtil.copyProperties(submitDTO, Orders.class);
        LocalDateTime now = LocalDateTime.now();
        orders.setNumber(String.valueOf(number)).setStatus(Orders.PENDING_PAYMENT).setUserId(userId)
                .setOrderTime(now).setPayStatus(Orders.UN_PAID).setUserName(user.getName())
                .setPhone(user.getPhone()).setAddress(address).setConsignee(addressByUserId.getConsignee());
        // 保存订单信息
        orderMapper.save(orders);
        // 订单id
        Long orderId = orders.getId();
        // 清空购物车
        shoppingCartMapper.delete(ShoppingCart.builder().userId(userId).build());
        // 向订单详情表中添加数据
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map(shoppingCart -> {
            OrderDetail orderDetail = BeanUtil.copyProperties(shoppingCart, OrderDetail.class);
            orderDetail.setOrderId(orderId);
            return orderDetail;
        }).collect(Collectors.toList());
        orderDetailMapper.saveBatch(orderDetailList);
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(String.valueOf(number))
                .orderAmount(submitDTO.getAmount())
                .orderTime(now)
                .build();
        return Result.success(orderSubmitVO);
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = UserHolder.get();
        User user = userMapper.getOne(User.builder().id(userId).build());

        //调用微信支付接口，生成预支付交易单
        // JSONObject jsonObject = weChatPayUtil.pay(
        //         ordersPaymentDTO.getOrderNumber(), //商户订单号
        //         new BigDecimal(0.01), //支付金额，单位 元
        //         "苍穹外卖订单", //商品描述
        //         user.getOpenid() //微信用户的openid
        // );
        JSONObject jsonObject = new JSONObject();

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
        // 通过websocket向客户端浏览器推送来单提醒
        Map<String, Object> map = new HashMap<>();
        // 1.表示来单提醒 2.表示客户催单
        map.put("type", 1);
        map.put("orderId", outTradeNo);
        map.put("content", "订单号：" + outTradeNo);
        String json = JSON.toJSONString(map);
        webSocketServer.sendAllClient(json);
    }

    @Override
    public Result<PageResult> pageList(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        ordersPageQueryDTO.setUserId(UserHolder.get());
        List<Orders> ordersList = orderMapper.list(ordersPageQueryDTO);
        if (CollectionUtil.isEmpty(ordersList)) {
            return Result.success(new PageResult(0, Collections.emptyList()));
        }
        List<OrderVO> orderVOList = ordersList.stream()
                .map(order -> BeanUtil.copyProperties(order, OrderVO.class))
                .collect(Collectors.toList());
        orderVOList.forEach(orderVO -> {
            Long orderId = orderVO.getId();
            List<OrderDetail> orderDetailList = orderDetailMapper.queryByOrderId(orderId);
            List<String> orderDishList = orderDetailList.stream().map(x -> {
                String orderDish = x.getName() + "*" + x.getNumber() + ";";
                return orderDish;
            }).collect(Collectors.toList());
            orderVO.setOrderDishes(String.join("", orderDishList));
            orderVO.setOrderDetailList(orderDetailList);
        });
        PageInfo<OrderVO> pageInfo = new PageInfo<>(orderVOList);
        return Result.success(new PageResult(pageInfo.getTotal(), pageInfo.getList()));
    }

    @Override
    public Result<OrderVO> getOrderDetail(Long id) {
        Orders orders = orderMapper.queryById(id);
        if (Objects.isNull(orders)) {
            return Result.error("暂无该订单信息");
        }
        OrderVO orderVO = BeanUtil.copyProperties(orders, OrderVO.class);
        List<OrderDetail> orderDetailList = orderDetailMapper.queryByOrderId(id);
        orderVO.setOrderDetailList(orderDetailList);
        return Result.success(orderVO);
    }

    @Override
    public Result<String> adminCancel(OrdersCancelDTO ordersCancelDTO) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.queryById(ordersCancelDTO.getId());

        // 支付状态
        // Integer payStatus = ordersDB.getPayStatus();
        // if (payStatus == 1) {
        //     //用户已支付，需要退款
        //     String refund = null;
        //     try {
        //         refund = weChatPayUtil.refund(
        //                 ordersDB.getNumber(),
        //                 ordersDB.getNumber(),
        //                 new BigDecimal(0.01),
        //                 new BigDecimal(0.01));
        //     } catch (Exception e) {
        //         throw new RuntimeException("退款失败");
        //     }
        //     log.info("申请退款：{}", refund);
        // }

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
        return Result.success();
    }

    /**
     * 用户取消订单
     * @param orders
     * @return
     */
    @Override
    @Transactional
    public Result<String> cancel(Orders orders) {
        Long orderId = orders.getId();
        Orders ordersDB = orderMapper.queryById(orderId);
        if (Objects.isNull(orderId)) {
            return Result.error("请选择你要取消的订单");
        }
        Orders ordersById = orderMapper.queryById(orderId);
        if (Objects.isNull(ordersById)) {
            return Result.error("暂无该订单信息");
        }
        // 只有处于待接单的使用用户才可以取消
        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 订单处于待接单状态下取消，需要进行退款
        // if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            // 调用微信支付退款接口
            // try {
            //     weChatPayUtil.refund(
            //             ordersDB.getNumber(), //商户订单号
            //             ordersDB.getNumber(), //商户退款单号
            //             new BigDecimal(0.01),//退款金额，单位 元
            //             new BigDecimal(0.01));//原订单金额
            // } catch (Exception e) {
            //     throw new RuntimeException("退款失败");
            // }

            // 支付状态修改为 退款
            // orders.setPayStatus(Orders.REFUND);
        // }
        orders.setCancelTime(LocalDateTime.now()).setStatus(Orders.CANCELLED);
        orderMapper.update(orders);
        orders.setCancelReason("用户取消");
        // 第一次做苍穹外卖 不需要删除订单 以便未来查看
        // 删除订单详情
        // orderDetailMapper.deleteByOrderId(orderId);
        return Result.success("取消成功");
    }

    @Override
    @Transactional
    public Result<String> repetition(Long id) {
        // 再来一单的意思是放到购物车中
        Orders orders = orderMapper.queryById(id);
        if (Objects.isNull(orders)) {
            return Result.error("再来一单失败");
        }
        List<OrderDetail> orderDetailList = orderDetailMapper.queryByOrderId(id);
        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(UserHolder.get());
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartMapper.saveBatch(shoppingCartList);
        return Result.success();
    }

    @Override
    public Result<OrderStatisticsVO> statistics() {
        List<Orders> ordersList = orderMapper.statistics();
        Integer toBeConfirmed = 0;
        Integer confirmed = 0;
        Integer deliveryInProgress = 0;
        for (Orders orders : ordersList) {
            Integer status = orders.getStatus();
            switch (status){
                case 2:
                    toBeConfirmed++;
                    break;
                case 3:
                    confirmed++;
                    break;
                case 4:
                    deliveryInProgress++;
            }
        }
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO(toBeConfirmed, confirmed, deliveryInProgress);
        return Result.success(orderStatisticsVO);
    }

    @Override
    public Result<String> confirm(Orders orders) {
        if (Objects.isNull(orders.getId())) {
            return Result.error("请选择你要接单的单子");
        }
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
        return Result.success();
    }

    @Override
    public Result<String> rejection(Orders orders) {
        if (Objects.isNull(orders.getId())) {
            return Result.error("请选择你要拒单的单子");
        }
        if (StrUtil.isBlank(orders.getRejectionReason())) {
            return Result.error("请选择拒单原因");
        }
        Long orderId = orders.getId();
        Orders orderDB = orderMapper.queryById(orderId);
        // 订单只有存在且状态为2（待接单）才可以拒单
        if (orderDB == null || !orderDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 支付状态
        // Integer payStatus = orderDB.getPayStatus();
        // if (payStatus == Orders.PAID) {
        //     //用户已支付，需要退款
        //     String refund = null;
        //     try {
        //         refund = weChatPayUtil.refund(
        //                 orderDB.getNumber(),
        //                 orderDB.getNumber(),
        //                 new BigDecimal(0.01),
        //                 new BigDecimal(0.01));
        //     } catch (Exception e) {
        //         throw new RuntimeException("退款失败");
        //     }
        //     log.info("申请退款：{}", refund);
        // }
        // 退款
        orders.setStatus(Orders.CANCELLED);
        orders.setPayStatus(Orders.REFUND);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
        return Result.success();
    }

    @Override
    public Result<String> delivery(Long id) {
        if (Objects.isNull(id)) {
            return Result.error("派单失败");
        }
        // 根据id查询订单
        Orders ordersDB = orderMapper.queryById(id);

        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        orderMapper.update(orders);
        return Result.success();
    }

    @Override
    public Result<String> complete(Long id) {
        if (Objects.isNull(id)) {
            return Result.error("派单失败");
        }
        // 根据id查询订单
        Orders ordersDB = orderMapper.queryById(id);

        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = Orders.builder()
                .id(id)
                .deliveryTime(LocalDateTime.now())
                .status(Orders.COMPLETED)
                .build();
        orderMapper.update(orders);
        return Result.success();
    }

    /**
     * 检查客户的收货地址是否超出配送范围
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }

    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.queryById(id);
        if (Objects.isNull(orders)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Map<String, Object> map = new HashMap<>();
        // 1.表示来单提醒 2.表示客户催单
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "订单号" + id);
        webSocketServer.sendAllClient(JSON.toJSONString(map));
    }

}
